<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2024/1/26
 * Time: 10:16
 */

namespace app\admin\controller;

use think\Db;
use think\Request;

class Member extends Base
{
    /**
     * 用户首页
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $user_email = input('user_email');
            $user_xing = input('user_xing');
            $user_name = input('user_name');
            $user_status = input('user_status');

            $where['user_status'] = ['<>', 5];
            if($user_email) $where['user_email'] = ['LIKE', '%' . $user_email . '%'];
            if($user_xing) $where['user_xing'] = ['LIKE', '%' . $user_xing . '%'];
            if($user_name) $where['user_name'] = ['LIKE', '%' . $user_name . '%'];
            if($user_status) $where['user_status'] = $user_status;

            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_u_user')->where($where)->count();// 获取总条数
            $lists = Db::table('up_u_user')
                ->where($where)
                ->field([
                    'user_id',
                    'user_email',
                    'user_xing',
                    'user_name',
                    'user_phone',
                    'user_company',
                    'user_position',
                    'user_status',
                    'user_time',
                    'user_type'
                ])
                ->page($Nowpage, $limits)
                ->order('user_time desc')
                ->select();

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }

    /**
     * 详情
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function memberDetail(){
        $user_id = input('user_id');
        $data = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->field([
                'user_id',
                'user_email',
                'user_xing',
                'user_name',
                'user_phone',
                'user_company',
                'user_position',
                'user_status',
                'user_time',
                'user_check_time',
                'user_refuse_reason'
            ])
            ->find();
        return $this->fetch('', ['data' => $data]);
    }

    /**
     * 审核通过
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function checkPass(){
        $user_id = input('user_id');
        if(Request::instance()->isPost()){
            $user_auth = input('user_auth');
            $user_email = input('user_email');
            $user_password = input('user_password');
            $user_pwd = input('user_pwd');

            if($user_auth == 1){
                if(!$user_email) return json(['code' => 100, 'msg' => '请填写邮箱']);
                if(!$user_password) return json(['code' => 100, 'msg' => '请填写密码']);
                if(!$user_pwd) return json(['code' => 100, 'msg' => '请确认密码']);
                if($user_password != $user_pwd) return json(['code' => 100, 'msg' => '两次密码不一致']);
                $user_leader = 1;
            }else{
                $user_leader = 2;
            }

            $update = [
                'user_type' => 1,
                'user_auth' => $user_auth,
                'user_leader' => $user_leader,
                'user_status' => 2,
                'user_check_time' => initTime()
            ];

            Db::startTrans();
            try{
                if($user_auth == 1){ // 上级领导
                    $upUser = Db::table('up_u_user')->where('user_email', $user_email)->find();
                    // 上级领导
                    if($upUser){
                        $f_id = $upUser['user_id'];
                    }else{
                        $f_id = Db::table('up_u_user')->insertGetId([
                            'user_email' => $user_email,
                            'user_password' => md5($user_password),
                            'user_time' => initTime()
                        ]);
                    }
                }else{
                    $f_id = 0;
                }

                $update['user_f_id'] = $f_id;

                Db::table('up_u_user')->where('user_id', $user_id)->update($update);

                Db::commit();
                return json(['code' => 200, 'msg' => '操作成功']);
            }catch (\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => $e->getMessage()]);
            }
        }
        return $this->fetch('', ['user_id' => $user_id]);
    }

    /**
     * 前端修改资料后重新审核
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function confirmCheckPass(){
        $user_id = input('id');

        $user = Db::table('up_u_user')->where('user_id', $user_id)->field('user_status')->find();
        if($user['user_status'] != 1) return json(['code' => 100, 'msg' => '用户状态异常']);

        $res = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->update([
                'user_status'     => 2,
                'user_check_time' => initTime()
            ]);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }

    /**
     * 拒绝
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function checkRefuse(){
        $user_id = input('user_id');
        if(Request::instance()->isPost()){
            $reason = input('reason');

            $res = Db::table('up_u_user')
                ->where('user_id', $user_id)
                ->update([
                    'user_status'        => 3,
                    'user_check_time'    => initTime(),
                    'user_refuse_reason' => $reason
                ]);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        return $this->fetch('', ['user_id' => $user_id]);
    }

    /**
     * 编辑
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function memberEdit(){
        $user_id = input('user_id');
        if(Request::instance()->isPost()){
            $xing = input('xing');
            $name = input('name');
            $phone = input('phone');
            $company = input('company');
            $position = input('position');

            $update = [
                'user_xing'        => $xing,
                'user_name'        => $name,
                'user_phone'       => $phone,
                'user_company'     => $company,
                'user_position'    => $position,
                'user_update_time' => initTime()
            ];
            $res = Db::table('up_u_user')->where('user_id', $user_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        $data = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->field('user_xing, user_name, user_phone, user_company, user_position')
            ->find();
        $this->assign([
            'data'    => $data,
            'user_id' => $user_id
        ]);
        return $this->fetch();
    }

    /**
     * 变更状态
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changeStatus(){
        $user_id = input('id');
        $user = Db::table('up_u_user')->where('user_id', $user_id)->field('user_status')->find();

        if($user['user_status'] == 2){
            $newStatus = 4;
        }elseif ($user['user_status'] == 4){
            $newStatus = 2;
        }else{
            return json(['code' => 100, 'msg' => '用户状态异常']);
        }

        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', $newStatus);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }

    /**
     * 删除
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function memberDel(){
        $user_id = input('id');

        $user = Db::table('up_u_user')->where('user_id', $user_id)->field('user_status')->find();
        if($user['user_status'] == 5){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', 5);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
    }

    /**
     * 修改收藏
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function memberCollect(){
        $goodsIDs = Db::table('up_goods_collect')
            ->where('collect_user_id', session('userID'))
            ->column('collect_goods_id');
        if(Request::instance()->isPost()){
            $ids = input('ids');
            $ids = explode(',', $ids);
            if($ids){
                $new = array_merge($ids, $goodsIDs); // 合并数组
                $incDiff = array_diff($new, $goodsIDs); // 需要新增的
                $decDiff = array_diff($new, $ids); // 需要删除的

                $incAll = [];
                if($incDiff){
                    foreach ($incDiff as $k => $v){
                        $incAll[$k] = [
                            'collect_user_id' => session('userID'),
                            'collect_goods_id' => $v
                        ];
                    }
                }
                Db::startTrans();
                try{
                    if($incAll){
                        Db::table('up_goods_collect')->insertAll($incAll);
                    }
                    if($decDiff){
                        Db::table('up_goods_collect')
                            ->where('collect_user_id', session('userID'))
                            ->where('collect_goods_id', 'IN', $decDiff)
                            ->delete();
                    }

                    Db::commit();
                    return json(['code' => 200, 'msg' => '操作成功']);
                }catch (\Exception $e){
                    Db::rollback();
                    return json(['code' => 100, 'msg' => $e->getMessage()]);
                }

            }else{
                $res = Db::table('up_goods_collect')->where('collect_user_id', session('userID'))->delete();
                if($res){
                    return json(['code' => 200, 'msg' => '操作成功']);
                }else{
                    return json(['code' => 100, 'msg' => '操作失败']);
                }
            }
        }
        $user_id = input('user_id');
        if($user_id) session('userID', $user_id);
        $goods = Db::table('up_goods')->where('goods_status', 1)
            ->field('goods_id, goods_name_en, goods_name_es, goods_name_tp')
            ->select();
        return $this->fetch('', ['IDS' => implode(',', $goodsIDs), 'goods' => $goods]);
    }
}